const app = getApp()

Page({
  data: {
    status: '请选择JPG文件'
  },

  chooseImage() {
    wx.chooseImage({
      count: 1,
      sizeType: ['original'],
      sourceType: ['album'],
      success: res => {
        this.processImage(res.tempFilePaths[0])
      }
    })
  },

  async processImage(tempFilePath) {
    this.setData({ status: '文件上传中...' })
    
    try {
      // 上传到云存储
      const uploadRes = await wx.cloud.uploadFile({
        cloudPath: `temp/${Date.now()}.jpg`,
        filePath: tempFilePath
      })

      // 调用云函数
      const res = await wx.cloud.callFunction({
        name: 'convertJpgToDoc',
        data: {
          fileID: uploadRes.fileID,
          originalPath: tempFilePath
        }
      })

      // 保存文件到本地
      wx.saveFile({
        tempFilePath: res.result.fileContent,
        success: saveRes => {
          this.setData({ 
            status: `文件已保存到：${saveRes.savedFilePath}`
          })
        }
      })
    } catch (e) {
      this.setData({ status: '转换失败：' + e.errMsg })
    }
  }
})
